package game.leon.engine.net.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/**
 * User: bianpeng
 * Date: 11-12-28
 */
class GameProtocolDecoder extends CumulativeProtocolDecoder {
    private static final String DECODE_STATE = "DECODE_STATE";
    public static final int BUFFER_PREFIX_LENGTH = 6;
    @Override
    protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
        DecodeState state = (DecodeState) session.getAttribute(DECODE_STATE);
        if (state == null) {
            state = new DecodeState();
            session.setAttribute(DECODE_STATE, state);
        }

        if (state.step == 0) {
            if (in.remaining() > BUFFER_PREFIX_LENGTH) {
                // 这里是实际数据长度, 8字节的PREFIX长度, 不包含在内
                state.datasize = in.getUnsignedShort();
                state.checksum = in.getUnsignedShort();
                state.flag = in.getUnsignedShort();

                state.step = 1;
            }
        }
        if (state.step == 1 && in.remaining() >= state.datasize) {
            int message = in.getUnsignedShort();
            byte[] data = new byte[state.datasize - 2];
            in.get(data);
            out.write(new GameRawMessage(message, data));
            state.step = 0;
            return true;
        }
        return false;
    }
    private static class DecodeState {
        int step;
        // 2 bytes data size
        // 2 bytes checksum
        // 2 bytes flag
        // 2 bytes message
        int datasize;
        int checksum;
        int flag;
    }
}
